package org.ucas.faker.web.fetcher;

import org.ucas.faker.web.fetcher.cond.FetchCond;
import org.ucas.faker.web.fetcher.meta.FetchField;
import org.ucas.faker.web.fetcher.meta.Table;
import org.ucas.faker.web.fetcher.op.GroupBy;
import org.ucas.faker.web.fetcher.op.Limit;
import org.ucas.faker.web.fetcher.op.OrderBy;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class AssembleRequest implements FetchRequest, Serializable {

  List<FetchField> fields = new ArrayList<>();

  Table from;

  FetchCond cond;

  GroupBy group;

  OrderBy order;

  Limit limit;


  @Override
  public String sql() {
    String res = "SELECT ";
    res += fields.stream().map(FetchField::sql).collect(Collectors.joining(","));
    res += " FROM " + from.sql();
    if(cond != null) res += " WHERE " + cond.sql();
    if(group != null) res += " " + group.sql();
    if(order != null) res += " " + order.sql();

    if(limit != null) res += " " + limit.sql();

    return res;
  }

  @Override
  public List<FetchField> selects() {
    return fields;
  }
}
